﻿local me = getLocalPlayer()
local view1stPersonEnabled = false




local function getPositionFromElementAtOffset ( element, x,y,z )
    if not x or not y or not z then  return false  end

    local matrix = getElementMatrix(element)

    local offX = x * matrix[1][1] + y * matrix[2][1] + z * matrix[3][1] + matrix[4][1]
    local offY = x * matrix[1][2] + y * matrix[2][2] + z * matrix[3][2] + matrix[4][2]
    local offZ = x * matrix[1][3] + y * matrix[2][3] + z * matrix[3][3] + matrix[4][3]

    return offX, offY, offZ
end

function set1stPersonCameraView()
    local _,_,myHeadZpos =      getPedBonePosition(me, 8)
    local _,_,myCenterZpos =    getElementPosition(me)

    local zOffset = myHeadZpos - myCenterZpos
    local pos =     { getPositionFromElementAtOffset( me, 0, 0.1, zOffset ) }
    local target =  { getPositionFromElementAtOffset( me, 0, 1, zOffset ) }

    local _,myYRotation = getElementRotation(me)

    setCameraMatrix( pos[1], pos[2], pos[3], target[1], target[2], target[3], myYRotation )
end




addEventHandler( "onClientPlayerVehicleEnter", me,
    function ( vehicle )
        if getVehicleType(vehicle) == 'Automobile' and not view1stPersonEnabled then
            addEventHandler( "onClientPreRender", root, set1stPersonCameraView )
            view1stPersonEnabled = true
        end
    end
)

addEventHandler( "onClientPlayerVehicleExit", me,
    function()
        if view1stPersonEnabled then
            removeEventHandler( "onClientPreRender", root, set1stPersonCameraView )
            setCameraTarget(me)
            view1stPersonEnabled = false
        end
    end
)
